package ddz.numerical;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kaka.numerical.TextNumericConfig;
import ddz.utils.JsonUtils;

import java.util.List;

public abstract class ConfManager<T> extends TextNumericConfig<T> {

    @Override
    protected String initDelimiter() {
        return "\t";
    }

    private final void parseToObject(JsonNode jsonNode, Class<T> beanClass) {
        if (jsonNode instanceof ObjectNode) {
            String json = JsonUtils.toJsonString(jsonNode);
            T info = JsonUtils.parseObject(json, beanClass);
            this.cacheObject(info);
        } else {
            ArrayNode jsonArray = (ArrayNode) jsonNode;
            for (int i = 0; i < jsonArray.size(); i++) {
                parseToObject(jsonArray.get(i), beanClass);
            }
        }
    }

    public final void parse(JsonNode jsonNode) {
        this.parseBefore();
        Class<T> beanClass = this.getMappingClass();
        parseToObject(jsonNode, beanClass);
        this.parseAfter();
    }

    abstract public List<T> getList();

}
